//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package appstore_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/appstore_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/appstore_api"
)

func (apiImpl *AppstoreApiImpl) ListApp(ctx context.Context, req *appstore_api.ListAppRequest) (*appstore_api.ListAppResponse, error) {
	userId := ""
	if req.SessionId != "" {
		sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
		if ok {
			userId = sessionItem.UserId
		}
	}

	count, err := appstore_dao.AppDao.Count(ctx, req.ListParam)
	if err != nil {
		return nil, err
	}
	appItemList, err := appstore_dao.AppDao.List(ctx, req.ListParam, int64(req.Offset), int64(req.Limit), req.SortKey)
	if err != nil {
		return nil, err
	}
	//补充分类信息
	cateIdList := []string{}
	appIdList := []string{}
	for _, appItem := range appItemList {
		appIdList = append(appIdList, appItem.AppId)
		if appItem.MajorCateId != "" {
			cateIdList = append(cateIdList, appItem.MajorCateId)
		}
		if appItem.MinorCateId != "" {
			cateIdList = append(cateIdList, appItem.MinorCateId)
		}
		if appItem.SubMinorCateId != "" {
			cateIdList = append(cateIdList, appItem.SubMinorCateId)
		}
	}
	cateItemList, err := appstore_dao.CateDao.ListById(ctx, cateIdList)
	if err != nil {
		return nil, err
	}
	cateNameMap := map[string]string{}
	for _, cateItem := range cateItemList {
		cateNameMap[cateItem.CateId] = cateItem.CateName
	}

	agreeMap := map[string]bool{}
	if userId != "" {
		//获取已点赞应用
		agreeAppIdList, err := appstore_dao.AgreeDao.DistinctAppId(ctx, appIdList, userId)
		if err != nil {
			return nil, err
		}
		for _, agreeAppId := range agreeAppIdList {
			agreeMap[agreeAppId] = true
		}
	}

	//生成结果
	appInfoList := []*appstore_api.AppInfo{}
	for _, appItem := range appItemList {
		appInfo := appItem.ToAppInfo()
		appInfo.MajorCate.CateName = cateNameMap[appInfo.MajorCate.CateId]
		appInfo.MinorCate.CateName = cateNameMap[appInfo.MinorCate.CateId]
		appInfo.SubMinorCate.CateName = cateNameMap[appInfo.SubMinorCate.CateId]
		appInfo.MyAgree = agreeMap[appItem.AppId]
		appInfoList = append(appInfoList, appInfo)
	}

	return &appstore_api.ListAppResponse{
		Code:        appstore_api.ListAppResponse_CODE_OK,
		TotalCount:  count,
		AppInfoList: appInfoList,
	}, nil
}

func (apiImpl *AppstoreApiImpl) ListAppById(ctx context.Context, req *appstore_api.ListAppByIdRequest) (*appstore_api.ListAppByIdResponse, error) {
	userId := ""
	if req.SessionId != "" {
		sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
		if ok {
			userId = sessionItem.UserId
		}
	}
	appItemList, err := appstore_dao.AppDao.ListById(ctx, req.AppIdList)
	if err != nil {
		return nil, err
	}
	//补充分类信息
	cateIdList := []string{}
	appIdList := []string{}
	for _, appItem := range appItemList {
		appIdList = append(appIdList, appItem.AppId)
		if appItem.MajorCateId != "" {
			cateIdList = append(cateIdList, appItem.MajorCateId)
		}
		if appItem.MinorCateId != "" {
			cateIdList = append(cateIdList, appItem.MinorCateId)
		}
		if appItem.SubMinorCateId != "" {
			cateIdList = append(cateIdList, appItem.SubMinorCateId)
		}
	}
	cateItemList, err := appstore_dao.CateDao.ListById(ctx, cateIdList)
	if err != nil {
		return nil, err
	}
	cateNameMap := map[string]string{}
	for _, cateItem := range cateItemList {
		cateNameMap[cateItem.CateId] = cateItem.CateName
	}

	agreeMap := map[string]bool{}
	if userId != "" {
		//获取已点赞应用
		agreeAppIdList, err := appstore_dao.AgreeDao.DistinctAppId(ctx, appIdList, userId)
		if err != nil {
			return nil, err
		}
		for _, agreeAppId := range agreeAppIdList {
			agreeMap[agreeAppId] = true
		}
	}

	//生成结果
	appInfoMap := map[string]*appstore_api.AppInfo{}
	for _, appItem := range appItemList {
		appInfo := appItem.ToAppInfo()
		appInfo.MajorCate.CateName = cateNameMap[appInfo.MajorCate.CateId]
		appInfo.MinorCate.CateName = cateNameMap[appInfo.MinorCate.CateId]
		appInfo.SubMinorCate.CateName = cateNameMap[appInfo.SubMinorCate.CateId]
		appInfo.MyAgree = agreeMap[appItem.AppId]
		appInfoMap[appItem.AppId] = appInfo
	}

	appInfoList := []*appstore_api.AppInfo{}
	for _, appId := range req.AppIdList {
		appInfo, ok := appInfoMap[appId]
		if ok {
			appInfoList = append(appInfoList, appInfo)
		}
	}

	return &appstore_api.ListAppByIdResponse{
		Code:        appstore_api.ListAppByIdResponse_CODE_OK,
		AppInfoList: appInfoList,
	}, nil
}

func (apiImpl *AppstoreApiImpl) ListAppByType(ctx context.Context, req *appstore_api.ListAppByTypeRequest) (*appstore_api.ListAppByTypeResponse, error) {
	userId := ""
	if req.SessionId != "" {
		sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
		if ok {
			userId = sessionItem.UserId
		}
	}
	appItemList, err := appstore_dao.AppDao.ListByType(ctx, uint32(req.AppType))
	if err != nil {
		return nil, err
	}
	//补充分类信息
	cateIdList := []string{}
	appIdList := []string{}
	for _, appItem := range appItemList {
		appIdList = append(appIdList, appItem.AppId)
		if appItem.MajorCateId != "" {
			cateIdList = append(cateIdList, appItem.MajorCateId)
		}
		if appItem.MinorCateId != "" {
			cateIdList = append(cateIdList, appItem.MinorCateId)
		}
		if appItem.SubMinorCateId != "" {
			cateIdList = append(cateIdList, appItem.SubMinorCateId)
		}
	}
	cateItemList, err := appstore_dao.CateDao.ListById(ctx, cateIdList)
	if err != nil {
		return nil, err
	}
	cateNameMap := map[string]string{}
	for _, cateItem := range cateItemList {
		cateNameMap[cateItem.CateId] = cateItem.CateName
	}

	agreeMap := map[string]bool{}
	if userId != "" {
		//获取已点赞应用
		agreeAppIdList, err := appstore_dao.AgreeDao.DistinctAppId(ctx, appIdList, userId)
		if err != nil {
			return nil, err
		}
		for _, agreeAppId := range agreeAppIdList {
			agreeMap[agreeAppId] = true
		}
	}

	//生成结果
	appInfoList := []*appstore_api.AppInfo{}
	for _, appItem := range appItemList {
		appInfo := appItem.ToAppInfo()
		appInfo.MajorCate.CateName = cateNameMap[appInfo.MajorCate.CateId]
		appInfo.MinorCate.CateName = cateNameMap[appInfo.MinorCate.CateId]
		appInfo.SubMinorCate.CateName = cateNameMap[appInfo.SubMinorCate.CateId]
		appInfo.MyAgree = agreeMap[appItem.AppId]
		appInfoList = append(appInfoList, appInfo)
	}

	return &appstore_api.ListAppByTypeResponse{
		Code:        appstore_api.ListAppByTypeResponse_CODE_OK,
		AppInfoList: appInfoList,
	}, nil
}

func (apiImpl *AppstoreApiImpl) GetApp(ctx context.Context, req *appstore_api.GetAppRequest) (*appstore_api.GetAppResponse, error) {
	userId := ""
	if req.SessionId != "" {
		sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
		if ok {
			userId = sessionItem.UserId
		}
	}

	emptyAppInfo := &appstore_api.AppInfo{
		BaseInfo:     &appstore_api.BaseAppInfo{},
		MajorCate:    &appstore_api.MajorCate{},
		MinorCate:    &appstore_api.MinorCate{},
		SubMinorCate: &appstore_api.SubMinorCate{},
		AppPerm: &appstore_api.AppPerm{
			NetPerm:   &appstore_api.AppNetPerm{},
			FsPerm:    &appstore_api.AppFsPerm{},
			ExtraPerm: &appstore_api.AppExtraPerm{},
		},
	}
	appItem, err := appstore_dao.AppDao.Get(ctx, req.AppId)
	if err != nil {
		return &appstore_api.GetAppResponse{
			Code:    appstore_api.GetAppResponse_CODE_NO_APP,
			ErrMsg:  "应用不存在",
			AppInfo: emptyAppInfo,
		}, nil
	}
	//补充分类信息
	cateIdList := []string{}
	if appItem.MajorCateId != "" {
		cateIdList = append(cateIdList, appItem.MajorCateId)
	}
	if appItem.MinorCateId != "" {
		cateIdList = append(cateIdList, appItem.MinorCateId)
	}
	if appItem.SubMinorCateId != "" {
		cateIdList = append(cateIdList, appItem.SubMinorCateId)
	}
	cateItemList, err := appstore_dao.CateDao.ListById(ctx, cateIdList)
	if err != nil {
		return nil, err
	}
	cateNameMap := map[string]string{}
	for _, cateItem := range cateItemList {
		cateNameMap[cateItem.CateId] = cateItem.CateName
	}
	//获取已点赞应用
	agreeAppIdList := []string{}
	if userId != "" {
		agreeAppIdList, err = appstore_dao.AgreeDao.DistinctAppId(ctx, []string{appItem.AppId}, userId)
		if err != nil {
			return nil, err
		}
	}

	//生成结果
	appInfo := appItem.ToAppInfo()
	appInfo.MajorCate.CateName = cateNameMap[appInfo.MajorCate.CateId]
	appInfo.MinorCate.CateName = cateNameMap[appInfo.MinorCate.CateId]
	appInfo.SubMinorCate.CateName = cateNameMap[appInfo.SubMinorCate.CateId]
	appInfo.MyAgree = len(agreeAppIdList) > 0

	return &appstore_api.GetAppResponse{
		Code:    appstore_api.GetAppResponse_CODE_OK,
		AppInfo: appInfo,
	}, nil
}

func (apiImpl *AppstoreApiImpl) InstallApp(ctx context.Context, req *appstore_api.InstallAppRequest) (*appstore_api.InstallAppResponse, error) {
	exist, err := appstore_dao.AppDao.Exist(ctx, req.AppId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &appstore_api.InstallAppResponse{
			Code:   appstore_api.InstallAppResponse_CODE_NO_APP,
			ErrMsg: "应用不存在",
		}, nil
	}
	err = appstore_dao.AppDao.IncInstallCount(ctx, req.AppId)
	if err != nil {
		return nil, err
	}

	return &appstore_api.InstallAppResponse{
		Code: appstore_api.InstallAppResponse_CODE_OK,
	}, nil
}

func (apiImpl *AppstoreApiImpl) QueryPerm(ctx context.Context, req *appstore_api.QueryPermRequest) (*appstore_api.QueryPermResponse, error) {
	emptyInfo := &appstore_api.AppPerm{
		NetPerm:   &appstore_api.AppNetPerm{},
		FsPerm:    &appstore_api.AppFsPerm{},
		ExtraPerm: &appstore_api.AppExtraPerm{},
	}
	appItem, err := appstore_dao.AppDao.Get(ctx, req.AppId)
	if err != nil {
		return &appstore_api.QueryPermResponse{
			Code:    appstore_api.QueryPermResponse_CODE_NO_APP,
			ErrMsg:  "应用不存在",
			AppPerm: emptyInfo,
		}, nil
	}
	app := appItem.ToAppInfo()
	return &appstore_api.QueryPermResponse{
		Code:    appstore_api.QueryPermResponse_CODE_OK,
		AppPerm: app.AppPerm,
	}, nil
}
